<?php

set_include_path(DOCUMENT_ROOT . '/library/');

require_once(DOCUMENT_ROOT . '/library/Erra/Utils/security.php');
require_once(DOCUMENT_ROOT . '/library/Erra/Utils/stdfuncs.php');

function default_resource_loading($buffer) {
    $isAdmin = (Erra_System_AccessControl::is('admin') || Erra_System_AccessControl::is('dev')) ? true : false;
    $public_path = config_get("application.http_webroot");

    // Mandatory js
    $offline_libraries = array('jquery' => $public_path . '/__erra/js/jquery/jquery-1.7.2.min.js');
    $online_libraries = array('jquery' => 'http://code.jquery.com/jquery-latest.min.js');

    $libraries = (config_get("optimization.online_libraries") == 1) ? $online_libraries : $offline_libraries;


    Erra_Core_HtmlStream::$js_framework[] = $libraries['jquery'];
    //Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery-migrate-1.0.0.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery.form.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery.cookie.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jstorage/jstorage.min.js';
    //Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery.ui.potato.menu-min.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery.tooltip.js'; // tipsy (github.com/jaz303)
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/colourpicker/jquery.colourpicker.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/outerHTML-2.1.0-min.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/framework.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/utils.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/ajax_forms.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/swfobject.js';

    // Include mandatory css
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/htmlbase.css';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/framework.css';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/framework.forms.common.css';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jquery.tooltip.css'; // tipsy (github.com/jaz303)
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/dynatree/ui.dynatree.css'; // tipsy (github.com/jaz303)
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jquery.colourpicker.css';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jquery.ui.timepicker.css'; //(http://fgelinas.com/code/timepicker/))

    if ($isAdmin) {
        Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jquery.ui.admin.menu.css';
    }

    if (config_get("debug.firebug_lite") == 1) {
        Erra_Core_HtmlStream::$js_framework[] = 'https://getfirebug.com/firebug-lite.js';
    }

    // Conditional include
    // FIXME : can we be more optimal ?
    if (Erra_System_PageBuilder::getCurrentPageName(0) == 'mail-sms') {
        Erra_Core_HtmlStream::$js[] = config_get("path.framework_js") . '/cleditor/jquery.cleditor.min.js';
        Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jquery.cleditor.css';
    }
    //  if (strstr($buffer, 'class="ui-') || (config_get('application.forms_theme') == 'jqueryui')) {
    Erra_Core_HtmlStream::$jsvar['JQUERYUI_ENABLED'] = 1;
    //Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jqueryui/jquery-ui-1.9.2.custom.min.js'; 
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jqueryui/jquery-ui-1.8.16.custom.min.js';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/jqueryui/jqueryui.css';
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/style/framework.forms.jqueryui.css';
    // More jQueryUI
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/timepicker/jquery.ui.timepicker.js'; //(http://fgelinas.com/code/timepicker/))
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/timepicker/jquery.ui.timepicker-fr.js'; //(http://fgelinas.com/code/timepicker/))
    Erra_Core_HtmlStream::$js_framework[] = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery.ui.datepicker-fr.min.js';
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/chosen/chosen.jquery.min.js'; // https://github.com/WilliamStam/jQuery-UI-select-menu
    Erra_Core_HtmlStream::$css_framework[] = $public_path . '/__erra/js/chosen/chosen.css'; // https://github.com/WilliamStam/jQuery-UI-select-menu
    //Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jquery/jquery.fastest.autocomplete.js'; // https://github.com/WilliamStam/jQuery-UI-select-menu


    /* } else {
      Erra_Core_HtmlStream::$jsvar['JQUERYUI_ENABLED'] = 0;
      } */

    if (strstr($buffer, 'erra-form-native-') || (config_get('application.forms_theme') == 'native')) {
        // Regenerate if production mode or dev mode
        $css_path = $public_path . '/__erra/style/framework.forms.native.css';
        if (Erra_Core_Config::get('application.production_mode') != 1) {
            Erra_System_FormRenderer_Native::generateCss($css_path);
        }
        Erra_Core_HtmlStream::$css_framework[] = $css_path;
    }

    if (strstr($buffer, 'erra-form-native-') || (config_get('application.forms_theme') == 'agenda')) {
        // Regenerate if production mode or dev mode
        $css_path = $public_path . '/__erra/style/framework.forms.agenda.css';
        Erra_Core_HtmlStream::$css_framework[] = $css_path;
    }

    if ((config_get('application.forms_theme') == 'custom' && $isAdmin)) {
        $css_path = $public_path . '/__erra/style/framework.forms.custom.css';
        Erra_Core_HtmlStream::$css_framework[] = $css_path;
    }

    if ($isAdmin) {
        Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/jqueryui/jquery-ui-1.8.16.sortable.slider.only.min.js';
        Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/nested.sortable/jquery.ui.nested.sortable.js';
    }
    // Editarea WYSIWYG code edit
    if (strstr($buffer, 'editareaZone')) {
        Erra_Core_HtmlStream::$jsnomerge[] = config_get("path.framework_js") . '/edit_area/edit_area_full.js';
    }

    // Framework UI
    Erra_Core_HtmlStream::$js_framework[] = $public_path . '/__erra/js/framework_ui.js';
    // CSS3 pie
    if (strstr($buffer, 'css3pie') && Browser::getSingleton()->getBrowser() == Browser::BROWSER_IE && Browser::getSingleton()->getVersion() <= 8) {
        Erra_Core_HtmlStream::$js[] = config_get("path.framework_js") . '/css3pie/PIE.js';
    }

    // Include javascript variables here
    Erra_Core_HtmlStream::$jsvar['WEBROOT'] = $public_path;
    Erra_Core_HtmlStream::$jsvar['IMAGES_FRAMEWORK'] = config_get("path.framework_images");
    Erra_Core_HtmlStream::$jsvar['IMAGES'] = config_get("path.public_images");
    Erra_Core_HtmlStream::$jsvar['POPUP_COUNTER'] = '0';
    Erra_Core_HtmlStream::$jsvar['INTERVAL'] = '0';
    Erra_Core_HtmlStream::$jsvar['LANG'] = LANG;
    Erra_Core_HtmlStream::$jsvar['RELOADING'] = Erra_Core_Locale::getReloadingMessage(LANG);
    Erra_Core_HtmlStream::$jsvar['CODE_200'] = '200';
    Erra_Core_HtmlStream::$jsvar['CODE_403'] = '403';
}

// Définition de l'encodage des caractère en UTF-8
if (function_exists('mb_internal_encoding')) {
    mb_internal_encoding('UTF-8');
}
// Définition du fuseau horaire
if (!defined('TIMEZONE')) {
    define('TIMEZONE', 'Europe/Paris');
}

date_default_timezone_set('Europe/Paris');

define('DEBUG_START', microtime(true));

// Enregistrement autoload
spl_autoload_register('erraAutoload');
// Error handler
Erra_Core_Kernel::setErrorHandler();



define('TIME', time());
// Si le client n'est pas en ligne de commande
if (isset($_SERVER['HTTP_HOST'])) {
    $sname = session_name();
    if (isset($_POST[$sname])) {
        $_COOKIE[$sname] = $_POST[$sname];
    } elseif (isset($_GET[$sname])) {
        $_COOKIE[$sname] = $_GET[$sname];
    }
    // Start session
    if (!defined('SESSION_START') || SESSION_START == true) {
        if (defined('SESSION_SAVE_PATH')) {
            session_save_path(SESSION_SAVE_PATH);
        }
        if (defined('SESSION_LIFETIME')) {
            Erra_Core_Kernel::startSession(config_get("application.session_lifetime"));
        } else {
            Erra_Core_Kernel::startSession();
        }
    }
    // Set UMASK (0022 = write right only open for current user)
    umask(0000);
} else {
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
    if (!isset($_SESSION)) {
        $_SESSION = array();
    }
}
// Shutdown
register_shutdown_function('__shutdown');
$__shutdown = array();


// Depending the server, path can be found in $_SERVER[ORIG_PATH_INFO]
if (!isset($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '') {
    if (isset($_SERVER['REDIRECT_STATUS']) && $_SERVER['REDIRECT_STATUS'] == 404) {
        http::head(200);
        $_SERVER['PATH_INFO'] = $_SERVER['REDIRECT_URL'];
        if (isset($_SERVER['REDIRECT_QUERY_STRING'])) {
            parse_str($_SERVER['REDIRECT_QUERY_STRING'], $_GET);
        }
    } else {
        if (isset($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] != '') {
            $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
        } else {
            $_SERVER['PATH_INFO'] = '';
        }
    }
    if ($_SERVER['PATH_INFO'] == '' && isset($_SERVER['QUERY_STRING']) && substr($_SERVER['QUERY_STRING'], 0, 1) == '/') {
        $s = Erra_Core_HtmlStream::multiExplode('?&', $_SERVER['REQUEST_URI']);
        $_SERVER['PATH_INFO'] = array_shift($s);
        $_SERVER['QUERY_STRING'] = implode('&', $s);
        parse_str($_SERVER['QUERY_STRING'], $_GET);
    }
}

function config_get($property) {
    return Erra_Core_Config::get($property);
}

Erra_Core_HttpFacade::getSingleton()->registerDefault(array('Erra_System_PageBuilder', 'hub'));
if (config_get("application.http_host") != config_get("application.http_webroot")) {
    $relativeWebrootUriPart = str_replace(config_get("application.http_host"), '', config_get("application.http_webroot"));
    $relativeWebrootUriPart = (strpos($relativeWebrootUriPart, '\\') == 0) ? substr($relativeWebrootUriPart, 1) : $relativeWebrootUriPart;
    $relativeWebrootUriPart = $relativeWebrootUriPart . '/';
} else {
    $relativeWebrootUriPart = '';
}

Erra_Core_HttpFacade::getSingleton()->register($relativeWebrootUriPart . 'POST_XMLHttpRequest', $relativeWebrootUriPart . 'POST_XMLHttpRequest', '^' . $relativeWebrootUriPart . 'POST_XMLHttpRequest(.*)$', array('Erra_System_XmlHttpRequest', 'handle'));

/* HYPER CACHE */
/* $cache_file = Erra_Utils_Tools::toUrlCompliant(str_replace(array('/', '-'), ' ', $_SERVER['REDIRECT_QUERY_STRING'])).'.cache';
  $compile_path = Erra_Core_Lexer::getCleanPath(DOCUMENT_ROOT . '/' . config_get("path.public_directory") . '/__cache/static_pages/' . $cache_file);
  if (file_exists($compile_path)) {
  $contents = file_get_contents($compile_path);
  echo $contents;
  FB::log('from cache');
  exit();
  } */


// [CACHE] : LOAD FROM HERE
ob_start();
echo Erra_Core_HttpFacade::getSingleton()->getDocument();
$buffer = ob_get_contents();
ob_end_clean();

function __($str) {
    return (!empty($GLOBALS['__l10n'][$str])) ? $GLOBALS['__l10n'][$str] : $str;
}

function erraAutoload($name) {
    // Appel des classes
    if ($name == 'FB') {
        require_once(DOCUMENT_ROOT . '/library/Erra/Externals/FirePHPCore/fb.php');
    } else if ($name == 'FirePHP') {
        require_once(DOCUMENT_ROOT . '/library/Erra/Externals/FirePHPCore/FirePHP.class.php');
    } else if ($name == 'Installer') {
        require_once(DOCUMENT_ROOT . '/install/Installer.php');
    } else if ($name == 'R') {
        require_once(DOCUMENT_ROOT . '/library/Redbean/rb.php');
        if (!isset(R::$toolboxes['default'])) {
            R::setup(config_get('db_driver') . ':host=' . config_get('db_host') . ';dbname=' . config_get('db_name'), config_get('db_user'), config_get('db_password'));
            R::freeze(true);
        }
    } else if ($name == 'PHPMailer') {
        if (file_exists(DOCUMENT_ROOT . '/library/Erra/Externals/PHPMailer/PHPMailer.php')) {
            require_once(DOCUMENT_ROOT . '/library/Erra/Externals/PHPMailer/PHPMailer.php');
        }
    } else if (stristr($name, 'PHPExcel')) {
        $path = str_replace('_', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/library/Erra/Externals/PHPExcel/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/library/Erra/Externals/PHPExcel/' . $path . '.php');
        }
    } else if (stristr($name, 'Slim')) {
        $path = str_replace('\\', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/library/Erra/Externals/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/library/Erra/Externals/' . $path . '.php');
        }
    } else if (stristr($name, 'Erra_')) {
        $path = str_replace('_', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/library/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/library/' . $path . '.php');
        }
    } else if (stristr($name, 'Erra\\')) {
        $path = str_replace('\\', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/library/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/library/' . $path . '.php');
        }
    } elseif (stristr($name, 'Zend')) {
        $path = str_replace('_', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/library/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/library/' . $path . '.php');
        }
    } elseif (strstr($name, 'Action')) {
        $path = str_replace('_', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/application/Actions/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/application/Actions/' . $path . '.php');
        }
    } elseif (strstr($name, 'Object')) {
        $path = str_replace('_', '/', $name);
        if (file_exists(DOCUMENT_ROOT . '/application/Objects/' . $path . '.php')) {
            require_once(DOCUMENT_ROOT . '/application/Objects/' . $path . '.php');
        }
    }
}

function __shutdown() {
    global $__shutdown;
    if (is_array($__shutdown)) {
        foreach ($__shutdown as $f) {
            if (is_callable($f)) {
                call_user_func($f);
            }
        }
    }
}

?>